import 'package:flutter/material.dart';

/// 改变焦点
/// 1. 创建FocusNode
/// 2. 通过FocusNode更改TextField焦点
/// 3. 点击按钮为FocusField设置焦点

class FocusChangeApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Focus Change Demo',
      theme: ThemeData(primarySwatch: Colors.red),
      home: FocusChangeAppPage(),
    );
  }
}

class FocusChangeAppPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _FocusChangeAppPageState();
}

class _FocusChangeAppPageState extends State<FocusChangeAppPage> {
  // 获取焦点对象
  FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    // 创建
    _focusNode = FocusNode();
  }

  @override
  void dispose() {
    // 销毁
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Focus Change Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              autofocus: true,
            ),
            TextField(
              focusNode: _focusNode,
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => FocusScope.of(context).requestFocus(_focusNode),
        tooltip: 'Focus Second Text Field.',
        child: Icon(Icons.edit),
      ),
    );
  }
}
